<template>
  <div id="Login">
    <div class="form-area">
      <Form ref="loginInfo" :model="loginInfo" label-position="top" :rules="rules">
          <FormItem label="账号" prop="account">
            <Input type="text" v-model="loginInfo.account" />
          </FormItem>
          <FormItem label="密码" prop="password">
            <Input type="password" v-model="loginInfo.password" @keyup.enter.native="handleSubmit('loginInfo')"/>
          </FormItem>
          <Form-item>
            <div class="foot">
              <Button type="primary" size="large" @click="handleSubmit('loginInfo')" @keyup.enter.native="handleSubmit('loginInfo')">提交</Button>
              <Button style="margin-left: 8px" size="large" @click="handleReset('loginInfo')">取消</Button>
            </div>
          </Form-item>
      </Form>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };
    return {
      rules: {
        account: [
          { type: 'string', min: 6, max: 20, message: '账户不为空' }
        ],
        password: [
          { validator: validatePass, trigger: 'blur' }
        ]
      },
      loginInfo: {
        account: 'cccccc',
        password: 'cccccc'
      }
    };
  },
  methods: {
    handleSubmit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          // this.$Message.success('提交成功!');
          // 登录
          this.$store.dispatch('user/Login', this.loginInfo).then((res) => {
            console.log(res);
            if (res.token) {
              // 登录成功获取用户信息
              this.$store.dispatch('user/getUserInfo', res.token).then((response) => {
                console.log(response);
                this.$router.push({ path:'/layout' });
              }).catch((err) => {
                console.log(err);
              });
            } else {
              console.log('获取token信息失败');
            }
          }).catch((err) => {
            console.log(err);
          });
        } else {
          this.$Message.error('表单验证失败!');
        }
      });
    },
    handleReset(name) {
      this.$refs[name].resetFields();
    }
  }
};
</script>

<style lang="scss" scoped>
#Login{
  width: 100%;
  height: 100vh;
  background-color: $login-bg;
  @include Center;
  .form-area{
    width: 30%;
    background: rgba(255,255,255,0.6);
    text-align: left;
    padding: 4rem;
    border-radius: 1rem;
  }

  .ivu-btn-large{
    width: 5rem;
  }
}
.foot{
  text-align: center;
}
</style>
